package cron

import (
	"encoding/json"
	"errors"
	"fmt"
	"likeadmin/admin/schemas/resp"
	"likeadmin/core"
	"likeadmin/core/response"
	"likeadmin/model/client"
	"likeadmin/util"
	"log"
	"strings"
	"time"

	"github.com/unknwon/com"
	"gorm.io/gorm"
)

type TaskService struct {
	db *gorm.DB
}

func NewCronService(db *gorm.DB) *TaskService {
	return &TaskService{
		db: db,
	}
}

func (cs *TaskService) ProcessOrder() {
	fmt.Println("处理订单任务执行:", time.Now().Format("2006-01-02 15:04:05"))
	// 处理具体业务逻辑
}

func (cs *TaskService) CleanLog() {
	fmt.Println("清理日志任务执行:", time.Now().Format("2006-01-02 15:04:05"))
	// 清理过期日志
}

func (cs *TaskService) RegisterAllTasks() {
	tasks := []struct {
		name     string
		schedule string
		function func()
	}{
		{"oppo成本实时获取任务", "59 */5 * * * *", cs.oppoAdDataToday},
		{"oppo成本昨天获取任务", "0 0 1 * * *", cs.oppoAdDataYesterday},
		{"头条成本实时获取任务", "59 */2 * * * *", cs.oceanengineAdDataToday},
		{"头条成本昨天获取任务", "0 5 1 * * *", cs.oceanengineAdDataYesterday},
		{"头条更新token", "59 */10 * * * *", cs.oceanengineRefreshToken},
		{"头条首单回传", "0 */3 * * * *", cs.callBack},
		{"统计充值", "59 */2 * * * *", cs.rechargeBusiness},
		{"统计今日粉丝", "59 */5 * * * *", cs.rechargeUsers},
	}

	registeredCount := 0
	for _, task := range tasks {
		if _, err := core.Cron.AddFunc(task.schedule, task.function); err != nil {
			fmt.Printf("警告: %s 注册失败: %v\n", task.name, err)
		} else {
			fmt.Printf("成功注册 %s\n", task.name)
			registeredCount++
		}
	}

	fmt.Printf("总共注册 %d 个定时任务\n", registeredCount)
}

func (cs *TaskService) oceanengineAdDataToday() {
	var accounts []client.Account
	err := cs.db.Model(&client.Account{}).Where("channel = ? AND status = ?", 1, 1).Find(&accounts).Error
	// 校验
	if e := response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
		fmt.Printf("BearerToken Find err %v", e)
		return
	}

	if e := response.CheckErr(err, "BearerToken First err"); e != nil {
		return
	}

	day := time.Now().AddDate(0, 0, 0).Format("20060102")

	for _, account := range accounts {
		// 每次执行停留0.1秒，避免频繁请求
		time.Sleep(200 * time.Millisecond)
		cost, e := util.OceanengineCallbackUtil{}.AdDataOcean(account, day)
		fmt.Println(fmt.Sprintf("账号:%s 日期:%s 成本:%d 错误%v", account.AccountId, day, cost, e))
		if cost > 0 {
			err = cs.RechargeReportSave(account, day, cost)
			if err != nil {
				// 处理错误
				log.Printf("保存充值报表失败: %v", err)
			}
		}
	}
}

func (cs *TaskService) oceanengineAdDataYesterday() {
	var accounts []client.Account
	err := cs.db.Model(&client.Account{}).Where("channel = ? AND status = ?", 1, 1).Find(&accounts).Error
	// 校验
	if e := response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
		fmt.Printf("BearerToken Find err %v", e)
		return
	}

	if e := response.CheckErr(err, "BearerToken First err"); e != nil {
		return
	}

	day := time.Now().AddDate(0, 0, -1).Format("20060102")

	for _, account := range accounts {
		cost, e := util.OceanengineCallbackUtil{}.AdDataOcean(account, day)
		fmt.Println(fmt.Sprintf("账号:%s 日期:%s 成本:%d 错误%v", account.AccountId, day, cost, e))
		if cost > 0 {
			err = cs.RechargeReportSave(account, day, cost)
			if err != nil {
				// 处理错误
				log.Printf("保存充值报表失败: %v", err)
			}
		}
	}

}

func (cs *TaskService) oceanengineRefreshToken() {
	var accounts []client.Account
	err := cs.db.Model(&client.Account{}).
		Where("channel = ? AND status = ?", 1, 1).
		Find(&accounts).Error

	// 错误处理优化
	if errors.Is(err, gorm.ErrRecordNotFound) {
		core.Logger.Info("没有找到需要刷新token的账号")
		return
	}
	if err != nil {
		core.Logger.Errorf("查询账号失败: %v", err)
		return
	}

	if len(accounts) == 0 {
		core.Logger.Info("没有需要刷新token的活跃账号")
		return
	}

	currentTime := time.Now().Unix()
	successCount := 0
	failCount := 0

	// 用于去重的映射，键为账号唯一标识
	isExec := make(map[string]bool)

	for _, account := range accounts {
		// 生成账号的唯一标识
		accountKey := account.UserAccount + account.ButlerAccount + account.CompanyName

		// 如果账号已经处理过，则跳过
		if isExec[accountKey] {
			core.Logger.Debugf("账号 %s(%s) 已处理过，跳过",
				account.AccountId, account.AccountTitle)
			continue
		}

		if !cs.needTokenRefresh(account, currentTime) {
			core.Logger.Debugf("账号 %s(%s) token无需更新",
				account.AccountId, account.AccountTitle)
			continue
		}

		if err := cs.refreshSingleAccountToken(account, currentTime); err != nil {
			failCount++
			core.Logger.Errorf("刷新账号 %s token失败: %v",
				account.AccountId, err)
			// 继续处理其他账号，不立即返回
			continue
		}

		// 标记该账号已处理
		isExec[accountKey] = true
		successCount++
	}

	core.Logger.Infof("token刷新完成: 成功%d个, 失败%d个, 总计%d个, 去重后处理%d个",
		successCount, failCount, len(accounts), successCount+failCount)
}

// needTokenRefresh 检查是否需要刷新token
func (cs *TaskService) needTokenRefresh(account client.Account, currentTime int64) bool {
	// 如果token时间为0或剩余时间大于30分钟，则不需要刷新
	if account.AccessTokenTime <= 0 {
		return false
	}

	remainingTime := account.AccessTokenTime - currentTime
	return remainingTime <= 1800 // 30分钟
}

// refreshSingleAccountToken 刷新单个账号的token
func (cs *TaskService) refreshSingleAccountToken(account client.Account, currentTime int64) error {
	core.Logger.Infof("开始刷新账号token: 账号ID=%s, 名称=%s",
		account.AccountId, account.AccountTitle)

	// 调用刷新接口
	respOcea, err := util.OceanengineCallbackUtil{}.AccesstokenRefresh(
		account.RefreshToken,
		account.UserAccount,
		account.ButlerAccount,
	)
	if err != nil {
		return fmt.Errorf("调用刷新接口失败: %w", err)
	}

	// 验证响应数据
	accessToken, refreshToken, expiresIn, err := cs.validateRefreshResponse(respOcea)
	if err != nil {
		return err
	}

	// 更新数据库
	if err := cs.updateAccountToken(account, accessToken, refreshToken, expiresIn, currentTime); err != nil {
		return fmt.Errorf("更新数据库失败: %w", err)
	}

	core.Logger.Infof("账号token刷新成功: 账号ID=%s, 名称=%s",
		account.AccountId, account.AccountTitle)

	return nil
}

// validateRefreshResponse 验证刷新响应
func (cs *TaskService) validateRefreshResponse(resp map[string]interface{}) (string, string, int64, error) {
	if resp == nil {
		return "", "", 0, fmt.Errorf("响应数据为空")
	}

	// 检查错误码
	if code, ok := resp["code"].(float64); !ok || code != 0 {
		message := "未知错误"
		if msg, ok := resp["message"].(string); ok {
			message = msg
		}
		return "", "", 0, fmt.Errorf("接口返回错误: code=%v, message=%s", code, message)
	}

	// 检查data字段
	data, ok := resp["data"].(map[string]interface{})
	if !ok {
		return "", "", 0, fmt.Errorf("响应数据格式错误: data字段缺失或类型不正确")
	}

	// 获取access_token
	accessToken, ok := data["access_token"].(string)
	if !ok || accessToken == "" {
		return "", "", 0, fmt.Errorf("access_token为空或格式错误")
	}

	// 获取refresh_token（可选）
	refreshToken := ""
	if rt, ok := data["refresh_token"].(string); ok {
		refreshToken = rt
	}

	// 获取过期时间
	expiresIn := int64(86400) // 默认24小时
	if exp, ok := data["expires_in"].(float64); ok {
		expiresIn = int64(exp)
	}

	return accessToken, refreshToken, expiresIn, nil
}

// updateAccountToken 更新账号token信息
func (cs *TaskService) updateAccountToken(account client.Account, accessToken, refreshToken string, expiresIn, currentTime int64) error {
	updateData := client.Account{
		AccessToken:     accessToken,
		AccessTokenTime: currentTime + expiresIn - 3600, // 提前1小时刷新
	}

	// 如果返回了新的refresh_token，则更新
	if refreshToken != "" {
		updateData.RefreshToken = refreshToken
		updateData.RefreshTokenTime = currentTime + expiresIn - 3600
	}

	err := cs.db.Model(&client.Account{}).
		Where("user_account = ? AND butler_account = ? AND company_name = ?",
			account.UserAccount, account.ButlerAccount, account.CompanyName).
		Updates(updateData).Error

	if err != nil {
		return fmt.Errorf("数据库更新失败: %w", err)
	}

	return nil
}

func (cs *TaskService) oppoAdDataToday() {
	var accounts []client.Account
	err := cs.db.Model(&client.Account{}).Where("channel = ? AND status = ?", 4, 1).Find(&accounts).Error
	// 校验
	if e := response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
		fmt.Printf("BearerToken Find err %v", e)
		return
	}

	if e := response.CheckErr(err, "BearerToken First err"); e != nil {
		return
	}

	toDays := []string{
		time.Now().AddDate(0, 0, 0).Format("20060102"),
	}

	for _, day := range toDays {
		for _, account := range accounts {
			cost, e := util.OppoCallbackUtil{}.AdData(account, day, "DAY")
			fmt.Println(fmt.Sprintf("账号:%s 日期:%s 成本:%d 错误%v", account.AccountId, day, cost, e))
			if cost > 0 {
				err = cs.RechargeReportSave(account, day, cost)
				if err != nil {
					// 处理错误
					log.Printf("保存充值报表失败: %v", err)
				}
			}
		}
	}

}

func (cs *TaskService) oppoAdDataYesterday() {
	var accounts []client.Account
	err := cs.db.Model(&client.Account{}).Where("channel = ? AND status = ?", 4, 1).Find(&accounts).Error
	// 校验
	if e := response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
		fmt.Printf("BearerToken Find err %v", e)
		return
	}

	if e := response.CheckErr(err, "BearerToken First err"); e != nil {
		return
	}

	day := time.Now().AddDate(0, 0, 0).Format("20060102")

	for _, account := range accounts {
		cost, e := util.OppoCallbackUtil{}.AdData(account, day, "DAY")
		fmt.Println(fmt.Sprintf("账号:%s 日期:%s 成本:%d 错误%v", account.AccountId, day, cost, e))
		if cost > 0 {
			err = cs.RechargeReportSave(account, day, cost)
			if err != nil {
				// 处理错误
				log.Printf("保存充值报表失败: %v", err)
			}
		}
	}

}

func (cs *TaskService) callBack() {
	// 调用时处理错误
	err := cs.OrderCallBack()
	if err != nil {
		log.Printf("自动回传失败: %v", err)
		// 根据错误类型进行相应处理
	}
}

// RechargeReportSave 每日报表统计
func (cs *TaskService) RechargeReportSave(account client.Account, date string, cost uint) error {
	return cs.db.Transaction(func(tx *gorm.DB) error {
		// 解析日期字符串
		parsedTime, err := time.Parse("20060102", date)
		if err != nil {
			core.Logger.Info(fmt.Sprintf("每日报表统计-日期解析错误:%v", err))
			return err // 返回错误会自动回滚
		}
		// 格式化为目标格式
		formattedDate := parsedTime.Format("2006-01-02")

		var rechargeReport client.RechargeReport
		err = tx.Model(&client.RechargeReport{}).Where("account_id = ? AND date = ?", account.AccountId, formattedDate).Order("date desc").First(&rechargeReport).Error

		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 创建新记录
			err = tx.Model(&client.RechargeReport{}).Create(&client.RechargeReport{
				AccountId: account.AccountId,
				CreaterID: account.CreaterID,
				Cost:      cost,
				Year:      time.Now().Format("2006"),
				Month:     time.Now().Format("2006-01"),
				Date:      formattedDate,
			}).Error
			if err != nil {
				core.Logger.Info(fmt.Sprintf("每日报表统计-创建记录失败:%v", err))
				return err
			}
		} else if err != nil {
			// 查询出错
			core.Logger.Info(fmt.Sprintf("每日报表统计-查询记录失败:%v", err))
			return err
		} else {
			// 更新现有记录
			err = tx.Model(&client.RechargeReport{}).Where("account_id = ? AND date = ?", account.AccountId, formattedDate).Select("cost", "update_time").Updates(map[string]interface{}{
				"cost":        cost,
				"update_time": time.Now().Unix(),
			}).Error
			if err != nil {
				core.Logger.Info(fmt.Sprintf("每日报表统计-更新记录失败:%v", err))
				return err
			}
		}

		// 计算总成本
		var totalCost uint
		err = tx.Model(&client.RechargeReport{}).Where("account_id = ?", account.AccountId).Select("IFNULL(SUM(cost),0)").Scan(&totalCost).Error
		if err != nil {
			core.Logger.Info(fmt.Sprintf("每日报表统计-计算总成本失败:%v", err))
			return err
		}

		// 更新账户总成本
		err = tx.Model(&client.Account{}).Where("account_id = ?", account.AccountId).Select("cost", "update_time").Updates(map[string]interface{}{
			"cost":        totalCost,
			"update_time": time.Now().Unix(),
		}).Error

		if err != nil {
			core.Logger.Info(fmt.Sprintf("每日报表统计-更新账户失败:%v", err))
			return err
		}

		// 返回 nil 会自动提交事务
		return nil
	})
}

func (cs *TaskService) OrderCallBack() error {

	return cs.db.Transaction(func(tx *gorm.DB) error {
		// 获取今日0点的时间戳
		now := time.Now()
		year, month, day := now.Date()
		todayTime := time.Date(year, month, day, 0, 0, 0, 0, now.Location()).Unix()

		var order client.Orders
		err := tx.Model(&client.Orders{}).Where("create_time >= ? AND user_create_time >= ? AND is_pay = ? AND callback_status = ?", todayTime, todayTime, 1, 0).Order("create_time desc").First(&order).Error

		// 校验订单是否存在
		if e := response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
			core.Logger.Info(fmt.Sprintf("OrderCallBack-订单不存在:%v", err))
			return e
		}

		var obj client.Account
		err = tx.Model(&client.Account{}).Where("account_id = ?", order.AccountId).Limit(1).First(&obj).Error
		if e := response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
			core.Logger.Info(fmt.Sprintf("OrderCallBack Account Find err %v", e))
			return e
		}

		var huichuanRate resp.HuichuanRate
		if obj.HuichuanRate != "" {
			err = json.Unmarshal([]byte(obj.HuichuanRate), &huichuanRate)
			if err != nil {
				core.Logger.Info(fmt.Sprintf("OrderCallBack-解析回传率配置失败:%v", err))
				return fmt.Errorf("解析回传率配置失败: %w", err)
			}
		}

		if huichuanRate.HuichuanRatePay <= 0 {
			core.Logger.Info(fmt.Sprintf("OrderCallBack-回传率配置无需回传:%v", huichuanRate))
			return fmt.Errorf("回传率配置无效")
		}

		// 统计今日订单总数
		var orderTotal int64
		err = tx.Model(&client.Orders{}).Where("create_time >= ? AND user_create_time >= ? AND is_pay = ?", todayTime, todayTime, 1).Count(&orderTotal).Error
		if err != nil {
			core.Logger.Info(fmt.Sprintf("OrderCallBack-统计订单总数失败:%v", err))
			return fmt.Errorf("统计订单总数失败: %w", err)
		}

		// 统计今日已回传订单数
		var backTotal int64
		err = tx.Model(&client.Orders{}).Where("create_time >= ? AND user_create_time >= ? AND is_pay = ? AND callback_status = ?", todayTime, todayTime, 1, 1).Count(&backTotal).Error
		if err != nil {
			core.Logger.Info(fmt.Sprintf("OrderCallBack-统计已回传订单失败:%v", err))
			return fmt.Errorf("统计已回传订单失败: %w", err)
		}

		if backTotal > 0 && orderTotal > 0 {
			bl := int((backTotal * 100) / orderTotal) // 修正百分比计算
			if bl > huichuanRate.HuichuanRatePay {
				core.Logger.Info(fmt.Sprintf("OrderCallBack-回传率已达上限:%v", bl))
				return fmt.Errorf("回传率已达上限: %d%% > %d%%", bl, huichuanRate.HuichuanRatePay)
			}
		}

		// 查询回调信息
		var callbackInfo client.CallbackInfo
		err = tx.Model(&client.CallbackInfo{}).Where("source_id = ? AND ip = ? AND callback_status < ?", order.SourceId, order.PayIp, 2).Order("id desc").Limit(1).First(&callbackInfo).Error
		if e := response.CheckErrDBNotRecord(err, "OrderCallBack callbackInfo First err"); e != nil {
			core.Logger.Info(fmt.Sprintf("OrderCallBack callbackInfo First err %v", e))
			return e
		}

		// 解析链接数据为对象
		var reportData map[string]interface{}
		err = util.ToolsUtil.JsonToObj(callbackInfo.Link, &reportData)
		if err != nil {
			core.Logger.Info(fmt.Sprintf("OrderCallBack-回调数据解析失败:%v", err))
			return fmt.Errorf("回调数据解析失败: %w", err)
		}

		// 检查解析结果
		if reportData == nil {
			core.Logger.Info(fmt.Sprintf("OrderCallBack-回调数据解析结果为空"))
			return fmt.Errorf("回调数据解析结果为空")
		}

		// 根据渠道进行回传
		var callbackResult string
		var callbackError error

		switch callbackInfo.Channel {
		case 1: // 头条
			callbackResult, callbackError = util.OceanengineCallbackUtil{}.Callback(&util.AdCallback{
				CallbackURL:     reportData["callback_url"].(string),
				Action:          "PAY",
				MicroCreateTime: callbackInfo.CreateTime * 1000, // 转换为毫秒
				Money:           order.Money,
			})

		case 4: // OPPO
			reportData["id"] = com.ToStr(callbackInfo.ID)
			reportData["dataType"] = 16
			reportData["package_name"] = order.PackageName
			callbackResult = util.OppoCallbackUtil{}.UploadOppo(reportData)

		default:
			core.Logger.Error(fmt.Sprintf("OrderCallBack-不支持的渠道:%d", callbackInfo.Channel))
			return fmt.Errorf("不支持的渠道: %d", callbackInfo.Channel)
		}

		// 检查上报结果
		if callbackError != nil || strings.Contains(callbackResult, "::error") {
			core.Logger.Info(fmt.Sprintf("OrderCallBack 回传失败: 渠道=%d, 错误=%v", callbackInfo.Channel, callbackError))
			return fmt.Errorf("回传失败: %s", callbackResult)
		}

		// 更新回调状态
		callbackInfo.CallbackStatus = 2
		callbackInfo.UpdateTime = time.Now().Unix()
		err = tx.Save(&callbackInfo).Error
		if e := response.CheckErr(err, "OrderCallBack 保存回调信息失败"); e != nil {
			core.Logger.Info(fmt.Sprintf("OrderCallBack 订单回调状态更新失败:%v", e))
			return e
		}

		// 更新订单回调状态
		err = tx.Model(&order).Updates(map[string]interface{}{"callback_status": 1}).Error
		if e := response.CheckErr(err, "OrderCallBack 更新订单回调状态失败"); e != nil {
			core.Logger.Info(fmt.Sprintf("OrderCallBack 订单回调状态更新失败:%v", e))
			return e
		}

		core.Logger.Info(fmt.Sprintf("OrderCallBack 自动回传成功: %s", order.OutNo))

		return nil // 自动提交事务
	})
}

func (cs *TaskService) rechargeBusiness() {
	// 调用时处理错误
	err := cs.executeRechargeBusiness()
	if err != nil {
		log.Printf("统计充值失败: %v", err)
		// 根据错误类型进行相应处理
	}
}

// executeRechargeBusiness 执行充值业务逻辑
func (cs *TaskService) executeRechargeBusiness() error {

	tx := core.GetDB().Begin()
	if tx.Error != nil {
		return fmt.Errorf("开启事务失败: %w", tx.Error)
	}
	var err error
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			core.Logger.Errorf("处理订单消息异常回滚: Error=%v", r)
		} else if err != nil {
			tx.Rollback()
		}
	}()

	now := time.Now()
	todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	todayTime := todayStart.Unix()

	var orders []client.Orders
	err = tx.Model(&client.Orders{}).Where("create_time >= ? AND is_pay = ?", todayTime, 1).Order("create_time desc").Find(&orders).Error

	if e := response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
		core.Logger.Info(fmt.Sprintf("RechargeBusiness err %v", e))
		return e
	}
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return err
	}

	accounts := make(map[string]uint)

	for _, i2 := range orders {
		accounts[i2.AccountId] += i2.Money
	}

	for accountId, money := range accounts {
		if err = updateAccountRecharge(tx, accountId); err != nil {
			fmt.Printf("updateAccountRecharge err %v", err)
			continue
		}

		if err = updateSourceRecharge(tx, accountId); err != nil {
			fmt.Printf("updateSourceRecharge err %v", err)
			continue
		}

		if err = updateDailyRechargeReport(tx, accountId, money); err != nil {
			fmt.Printf("updateDailyRechargeReport err %v", err)
			continue
		}

	}

	if err = tx.Commit().Error; err != nil {
		return fmt.Errorf("提交事务失败: %w", err)
	}

	core.Logger.Infof("处理执行充值业务逻辑成功: Orders=%d, Accounts=%s", len(orders), len(accounts))
	return nil
}

// updateAccountRecharge 更新账户充值金额
func updateAccountRecharge(tx *gorm.DB, accountId string) error {
	var money uint
	if err := tx.Model(&client.Orders{}).Where("is_pay = ? AND account_id = ?", 1, accountId).Select("IFNULL(SUM(money), 0)").Scan(&money).Error; err != nil {
		money = 0
	}
	return tx.Model(&client.Account{}).
		Where("account_id = ?", accountId).
		Updates(map[string]interface{}{
			"recharge":    money,
			"update_time": time.Now().Unix(),
		}).Error
}

// updateSourceRecharge 更新渠道充值金额
func updateSourceRecharge(tx *gorm.DB, accountId string) error {
	var money uint
	if err := tx.Model(&client.Orders{}).Where("is_pay = ? AND account_id = ?", 1, accountId).Select("IFNULL(SUM(money), 0)").Scan(&money).Error; err != nil {
		money = 0
	}
	return tx.Model(&client.Source{}).
		Where("account_id = ?", accountId).
		Updates(map[string]interface{}{
			"recharge":    money,
			"update_time": time.Now().Unix(),
		}).Error
}

// updateDailyRechargeReport 更新每日充值报表
func updateDailyRechargeReport(tx *gorm.DB, accountId string, money uint) error {
	// 根据用户实际支付的时间，归属统计到那一天
	now := time.Now()
	payDate := now.Format("2006-01-02")
	var report client.RechargeReport

	err := tx.Model(&client.RechargeReport{}).
		Where("account_id = ? AND date = ?", accountId, payDate).
		First(&report).Error

	nowInt64 := now.Unix()
	if errors.Is(err, gorm.ErrRecordNotFound) {
		fmt.Printf("查询日报表失败: %v,accountId:%s", err, accountId)
	}
	err = updateExistingRechargeReport(tx, accountId, money, payDate, nowInt64)
	if err != nil {
		fmt.Printf("日报表更新失败: %v,accountId:%s", err, accountId)
	}

	return err
}

// updateExistingRechargeReport 更新现有的日报表记录
func updateExistingRechargeReport(tx *gorm.DB, accountId string, money uint, date string, timestamp int64) error {
	return tx.Model(&client.RechargeReport{}).
		Where("account_id = ? AND date = ?", accountId, date).
		Updates(map[string]interface{}{
			"recharge":       money,
			"total_recharge": money,
			"update_time":    timestamp,
		}).Error
}

func (cs *TaskService) rechargeUsers() {
	targetDate := time.Now()

	// 调用时处理错误
	err := cs.execRechargeUsers(targetDate)

	if err != nil {
		log.Printf("统计今日粉丝失败: %v", err)
		// 根据错误类型进行相应处理
	}

}

func (cs *TaskService) execRechargeUsers(targetDate time.Time) error {
	tx := core.GetDB().Begin()
	if tx.Error != nil {
		return fmt.Errorf("开启事务失败: %w", tx.Error)
	}
	var err error
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			core.Logger.Errorf("处理订单消息异常回滚: Error=%v", r)
		} else if err != nil {
			tx.Rollback()
		}
	}()

	now := targetDate
	toDay := now.Format("2006-01-02")

	// 获取今日0点的时间戳
	todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	todayTime := todayStart.Unix()

	// 获取所有活跃的账号
	var accounts []client.Account
	err = tx.Model(&client.Account{}).Where("status = ?", 1).Find(&accounts).Error
	if e := response.CheckErrDBNotRecord(err, "没有找到活跃账号!"); e != nil {
		core.Logger.Info(fmt.Sprintf("execRechargeUsers 查询账号失败: %v", e))
		return e
	}

	for _, account := range accounts {
		// 统计该账号的总用户数
		var totalUsers int64
		err = tx.Model(&client.ClientUser{}).Where("account_id = ?", account.AccountId).Count(&totalUsers).Error
		if err != nil {
			core.Logger.Errorf("统计账号 %s 总用户数失败: %v", account.AccountId, err)
			continue // 继续处理下一个账号，不中断整个流程
		}

		// 统计该账号的今日新增用户数
		var todayUsers int64
		err = tx.Model(&client.ClientUser{}).Where("account_id = ? AND create_time >= ? AND create_time < ?", account.AccountId, todayTime, todayTime+86400).Count(&todayUsers).Error
		if err != nil {
			core.Logger.Errorf("统计账号 %s 今日用户数失败: %v", account.AccountId, err)
			continue
		}

		// 更新或创建每日报表中的用户统计信息
		err = cs.updateDailyUserReport(tx, account.AccountId, toDay, int(totalUsers), int(todayUsers))
		if err != nil {
			core.Logger.Errorf("更新账号 %s 用户统计失败: %v", account.AccountId, err)
			continue
		}

		core.Logger.Debugf("账号 %s 用户统计完成: 总用户=%d, 今日新增=%d",
			account.AccountId, totalUsers, todayUsers)
	}

	if err = tx.Commit().Error; err != nil {
		return fmt.Errorf("提交事务失败: %w", err)
	}

	core.Logger.Infof("今日粉丝统计完成: 共处理 %d 个账号", len(accounts))
	return nil
}

// updateDailyUserReport 更新每日报表中的用户统计信息
func (cs *TaskService) updateDailyUserReport(tx *gorm.DB, accountId, date string, totalUsers, todayUsers int) error {
	var rechargeReport client.RechargeReport

	// 查找是否已存在该账号当天的记录
	err := tx.Model(&client.RechargeReport{}).
		Where("account_id = ? AND date = ?", accountId, date).
		First(&rechargeReport).Error

	now := time.Now()
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		// 账号统计用户总数
		err = tx.Model(&client.Account{}).
			Where("account_id = ?", accountId).
			Updates(map[string]interface{}{
				"users":       totalUsers,
				"update_time": now.Unix(),
			}).Error
		// 更新现有记录
		if err == nil {
			return tx.Model(&client.RechargeReport{}).
				Where("account_id = ? AND date = ?", accountId, date).
				Updates(map[string]interface{}{
					"users":       todayUsers,
					"update_time": now.Unix(),
				}).Error
		}
	}

	return err
}
